<script setup lang="tsx">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { type User, assignUserRole, fetchAllRolesOptions, fetchGetUserById } from '@/service/api';

defineOptions({
  name: 'UserAssignRoleModel'
});

interface Props {
  /** the edit row data */
  rowData?: User | null;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  return `${$t('page.manage.user.assignUserRole')}`;
});

type Model = Pick<User, 'username' | 'nickname' | 'roles'>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    username: '',
    nickname: '',
    roles: []
  };
}

type RuleKey = Extract<keyof Model, 'roles'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  roles: defaultRequiredRule
};

function closeDrawer() {
  visible.value = false;
}

const roleOptions = ref<CommonType.Option<string>[]>([]); // 角色列表
async function getRoleOptions() {
  const { error, data } = await fetchAllRolesOptions();

  if (!error) {
    const options = data.map(item => ({
      label: item.label,
      value: item.value
    }));

    roleOptions.value = [...options];
  }
}

async function handleSubmit() {
  await validate();

  if (!props.rowData) return;
  await assignUserRole(props.rowData.id, model.roles);

  window.$message?.success($t('common.addSuccess'));
  closeDrawer();
}

async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (!props.rowData) return;

  const res = await fetchGetUserById(props.rowData.id);

  Object.assign(model, res.data);
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getRoleOptions();
  }
});
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-180">
    <NScrollbar class="max-h-200 pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="100">
        <NFormItem :label="$t('page.manage.user.userName')" path="username">
          <NInput v-model:value="model.username" :placeholder="$t('page.manage.user.form.userName')" disabled />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.nickName')" path="nickname">
          <NInput v-model:value="model.nickname" :placeholder="$t('page.manage.user.form.nickName')" disabled />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userRole')" path="roles">
          <NSelect
            v-model:value="model.roles"
            multiple
            filterable
            :options="roleOptions"
            :placeholder="$t('page.manage.user.form.userRole')"
          />
        </NFormItem>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
